<?php

namespace App\Controller\Admin;

use App\Agent\ChatAgent;
use App\Constants\RedisKey;
use App\Middleware\AdminMiddleware;
use App\Model\AdminWord;
use Hyperf\Di\Annotation\Inject;
use Hyperf\WebSocketClient\ClientFactory;
use Hyperf\WebSocketClient\Exception\ConnectException;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\Utils\ApplicationContext;

#[Controller(prefix: '/admin/Word'), Middleware(AdminMiddleware::class)]
class WordController extends BaseController {

    /**
     * @Inject
     * @var ClientFactory
     */
    protected ClientFactory $clientFactory;

    /**
     * 获取列表
     * @return array
     */
    #[GetMapping(path: 'index')]
    public function index(): array {
        $limit = $this->request->query('size', config('apiadmin.admin_list_default'));
        $keywords = $this->request->query('keywords', '');

        $listObj = AdminWord::query();
        if ($keywords) {
            $listObj = $listObj->where('words', 'like', "%{$keywords}%");
        }
        $listObj = $listObj->orderByDesc('id')->paginate((int)$limit);

        return $this->buildSuccess([
            'list'  => $listObj->items(),
            'count' => $listObj->total(),
        ]);
    }

    /**
     * 添加
     * @return array
     */
    #[PostMapping(path: 'add')]
    public function add(): array {
        $confObj = new AdminWord();
        $confObj->words = $this->request->post('words', '');
        $confObj->save();
        return $this->buildSuccess();
    }

    /**
     * 删除
     * @return array
     */
    #[GetMapping(path: 'del')]
    public function del(): array {
        $id = $this->request->query('id');
        AdminWord::query()->where('id', $id)->delete();
        return $this->buildSuccess();
    }

    /**
     * 更新配置文件缓存
     */
    #[GetMapping(path: 'updateFile')]
    public function updateFile(): array {
        $redis = (ApplicationContext::getContainer())->get(ChatAgent::class);
        $fileKey = RedisKey::GM_CHAT_PRE . ':WordsFile';
        $list = AdminWord::query()->select('words')->get()->toArray();
        if ($redis->exists($fileKey)) {
            $redis->del($fileKey);
        }
        $redis->set($fileKey, json_encode(array_column($list, 'words')));
        try {
            $host = env('CHAT_HOST', '172.17.16.4') . ':' . env('CHAT_PORT', 8809) . '?User-Token=System';
            var_dump('聊天刷新host');
            var_dump($host);
            $client = $this->clientFactory->create($host);
            $res = $client->push('renew');
            var_dump('聊天刷新res');
            var_dump($res);
        } catch (ConnectException $e) {
            //var_dump(date('Y-m-d H:i:s') . '---消息发送错误---' . $e->getMessage());
        }
        return $this->buildSuccess();
    }

}